package com.zz.framework.core.adapter

import kotlin.properties.Delegates

/**
 * 封装一个kotlin下的通用adapter
 */
//val  adapter = KotlinAdapter.Builder<String>(R.layout.item_sorting_type_layout)
//    .setNewData(Lists.newArrayList())
//    .addBindView { holder, item ->
//    }
//    .onItemClick { holder, item -> kotlin.run {
//    }}
//    .create()
class KotlinAdapter<T: Any> private constructor(mLayoutId:Int) : BaseKotlinAdapter<T>(mLayoutId) {
    //绑定事件的lambda放发
    private var addBindView: ((BaseViewHolder, position: Int, T?) -> Unit)? = null
    //view被点击
    var itemClick: ((BaseViewHolder, position: Int, T?) -> Unit)? = null
    var itemLongClick: ((BaseViewHolder, position: Int, T?) -> Unit)? = null

    override fun convert(holder: BaseViewHolder, position: Int, item: T?) {
        addBindView?.invoke(holder, position,item)
        holder.itemView.setOnClickListener {
            itemClick?.invoke(holder, position, item)
        }
        itemLongClick?.let {
            holder.itemView.setOnLongClickListener { _->
                it.invoke(holder,  position,item)
                true
            }
        }
    }


    /**
     * 建造者，用来完成adapter的数据组合
     */
    class Builder<B:Any>(mLayoutId: Int) {

        private var adapter: KotlinAdapter<B> by Delegates.notNull()

        init {
            adapter =  KotlinAdapter(mLayoutId)
        }

        /**
         * 设置数据
         */
        fun setNewData(lists: List<B>?): Builder<B> {
            adapter.submitList(lists?.toMutableList())
            return this
        }

        /**
         * 绑定View和数据
         */
        fun addBindView(itemBind: ((holder: BaseViewHolder, position: Int, item: B?) -> Unit)): Builder<B> {
            adapter.addBindView = itemBind
            return this
        }

        /**
         * item点击回调
         */
        fun onItemClick(itemClick:(holder: BaseViewHolder, position: Int, item: B?) -> Unit): Builder<B> {
            adapter.itemClick = itemClick
            return this
        }

        fun onItemLongClick(itemClick:(holder: BaseViewHolder, position: Int, item: B?) -> Unit): Builder<B> {
            adapter.itemLongClick = itemClick
            return this
        }

        fun create(): KotlinAdapter<B> {
            return adapter
        }

    }



}